import { ref } from 'vue'
export function userList(config: any = {}) {
  const status = ref('loading')
  const tableData = ref<any[]>([])
  const queryForm = ref({
    current: 1,
    size: config?.size || 10
  })
  if (config?.initForm) {
    queryForm.value = {
      ...queryForm.value,
      ...JSON.parse(JSON.stringify(config.initForm))
    }
  }

  /**
   * 数据列表
   * */

  const fetchData = (param = {}) => {
    status.value = 'loading'
    const params = {
      ...queryForm.value,
      ...param
    }
    return config.apis
      .getApi(params)
      .then(data => {
        if (params.current === 1) {
          tableData.value = data.data
        } else {
          tableData.value = [...tableData.value, ...data.data]
        }
        status.value = params.size === data.data.length ? 'loadmore' : 'nomore'
        queryForm.value.current++
      })
      .catch(() => {})
  }

  const handDel = index => {
    tableData.value.splice(index, 1)
  }

  const onBottom = (callBack?: () => {}) => {
    if (status.value == 'nomore') return
    fetchData().then(() => {
      callBack && callBack()
    })
  }

  const onRefresh = () => {
    status.value = 'loading'
    tableData.value = []
    queryForm.value.current = 1
    fetchData()
  }

  return {
    fetchData,
    status,
    tableData,
    onBottom,
    onRefresh,
    handDel,
    queryForm
  }
}
